package com.dev.security.config.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.stereotype.Repository;

/**
 * 基础dao类
 * @author 潜行的青衣
 */
@Repository
public class BaseDao {

    private EntityManagerFactory emf; 
	
	@PersistenceUnit
    public void setEntityManagerFactory(EntityManagerFactory emf) {
        this.emf = emf;
    }
	
	/**
	 * 需要事物
	 * @author 潜行的青衣
	 * @version
	 * @return
	 */
	public EntityManager getEntityManager() {
		return EntityManagerFactoryUtils.getTransactionalEntityManager(emf);
	}
	
	public EntityManagerFactory getEntityManagerFactory() {
		return emf;
	}
	
	public CriteriaQuery<Object> createCriteriaQuery() {
		return this.getEntityManagerFactory().getCriteriaBuilder().createQuery();
	}
	
	public <T> CriteriaQuery<T> createCriteriaQuery(Class<T> clazz) {
		return this.getEntityManagerFactory().getCriteriaBuilder().createQuery(clazz);
	}
	
	public CriteriaBuilder getCriteriaBuilder() {
		return this.getEntityManagerFactory().getCriteriaBuilder();
	}
}
